package v1

import (
	"gin-example/models"
	"gin-example/pkg/e"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
	"log"
	"net/http"
)

func GetAllImages(c *gin.Context) {
	data := make(map[string]interface{})
	code := e.SUCCESS

	data["lists"] = models.GetImages()

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": data,
	})
}

func AddImage(c *gin.Context) {
	json := make(map[string]string)
	_ = c.BindJSON(&json)

	src := json["src"]
	zh_name := json["zh_name"]
	en_name := json["en_name"]

	valid := validation.Validation{}
	valid.Required(src, "src").Message("源地址不能为空")
	valid.Required(zh_name, "zh_name").Message("中文名称不能为空")
	valid.Required(en_name, "en_name").Message("英文名称不能为空")
	code := e.INVALID_PARAMS

	if !valid.HasErrors() {
		code = e.SUCCESS
		models.AddImage(src, zh_name, en_name)
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": make(map[string]string),
	})
}

func UpdateImage(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()
	code := e.INVALID_PARAMS

	if models.ExistImageByID(id) {
		code = e.SUCCESS
		json := make(map[string]interface{})
		_ = c.BindJSON(&json)
		models.UpdateImage(id, json)
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": make(map[string]string),
	})
}

func DeleteImage(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()
	code := e.INVALID_PARAMS
	if models.ExistImageByID(id) {
		models.DeleteImage(id)
		code = e.SUCCESS
	} else {
		code = e.ERROR_NOT_EXIST
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": make(map[string]string),
	})
}